package com.erp.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.jasper.tagplugins.jstl.core.ForEach;

import com.erp.po.Categorys;
import com.erp.po.Products;
import com.erp.po.Providers;
import com.erp.service.CategorysServiceImpl;
import com.erp.service.ProductsServiceImpl;
import com.erp.service.ProviderServiceImpl;
import com.erp.util.BootStrapPageHelper;
import com.erp.util.Page;
import com.google.gson.Gson;

public class ProductServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private ProductsServiceImpl ps;

	public ProductServlet() {
		ps = new ProductsServiceImpl();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 处理中文乱码
		/*request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");*/
		
		String op = request.getParameter("op");

		System.out.println("op: " + op + " ------- productServlet");
		if ("showProductByPage".equals(op)) {
			// 分页查询
			showProductByPage(request, response);
		} else if ("removeProductByproId".equals(op)) {
			// 删除
			removeProductByproId(request, response);
		} else if ("readyEditProductById".equals(op)) {
			// 准备修改
			readyEditProductById(request, response);
		} else if ("doEditProductById".equals(op)) {
			// 开始修改
			doEditProductById(request, response);
		} else if("readyAddProduct".equals(op)) {
			// 准备增加
			readyAddProduct(request, response);
		} else if("doAddProduct".equals(op)) {
			doAddProduct(request, response);
		} else if("checkProductNameByEdit".equals(op)) {
			// 修改校验重名
			checkProductNameByEdit(request, response);
		} else if("checkProductNameByAdd".equals(op)) {
			// 添加校验重名
			checkProductNameByAdd(request, response);
		} else if("seachBoth".equals(op)) {
			// ajax 查询 供应商,类别
			seachBoth(request, response);
		} else if("doSearchProducts".equals(op)) {
			// ajax 条件查询 数据
			doSearchProducts(request, response);
		}

	}
	
	/**
	 * ajax 条件查询 数据
	 */
	protected void doSearchProducts(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {

		String productName = request.getParameter("productName").trim();
		int categoryId = Integer.parseInt(request.getParameter("categorys"));
		int providerId = Integer.parseInt(request.getParameter("providers"));
		
		// limit : 5  页大小 ; offset : 0  忽略数[从0后开始];
		int offset = Integer.parseInt(request.getParameter("offset"));
		int pageSize = Integer.parseInt(request.getParameter("limit"));
		int currentPage = (offset / pageSize) + 1;
		
		
		Page<Products> page = ps.findProductsListByCondition(new Products(productName, new Providers(providerId), new Categorys(categoryId)), new Page<Products>(currentPage, pageSize));
		
		// 使用bootstrap-table时,需要用到 BootStrapPageHelper
		BootStrapPageHelper<Products> pageHelper = new BootStrapPageHelper<Products>();
		
		pageHelper.setTotal(page.getTotal());
		pageHelper.setRows(page.getList());
		
		Gson gson = new Gson();
		response.getWriter().print(gson.toJson(pageHelper));
	}

	/**
	 * ajax 查询 供应商,类别
	 */
	protected void seachBoth(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {

		// 类别
		CategorysServiceImpl cs = new CategorysServiceImpl();
		List<Categorys> cateList = cs.findCategorys();

		// 供应商
		ProviderServiceImpl prod = new ProviderServiceImpl();
		List<Providers> proList = prod.findProviders();
		
		Object[] arr = {cateList,proList}; 
		
		// 使用 gson 将 数组转为 json数据格式的字符串
		Gson gson = new Gson();
		String json = gson.toJson(arr);
		
		response.getWriter().print(json);
	}

	/**
	 * 添加校验重名
	 */
	protected void checkProductNameByAdd(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		
		String productName = request.getParameter("proName");
		String str = null;
		boolean b = ps.findProductByName(productName);
		if (b) {
			str = "可用";
		} else {
			str = "重名";
		}
		response.getWriter().print(str);
	}

	/**
	 * 校验重名
	 */
	protected void checkProductNameByEdit(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException{
		
		int productId = Integer.parseInt(request.getParameter("id"));
		// System.out.println(request.getParameter("id"));
		String productName = request.getParameter("proName");
		
		System.out.println(productName);
		
		String str = null;

		// 校验product重名
		Products products = ps.findProductByPName(productName);
		System.out.println((products.getProductId() == productId)+"------ servlet");
		
		boolean f = ps.findProductByName(productName);
		if (f) {
			str = "可用";
		} else {
			if(products.getProductId() == productId) {
				str = "可用";
			} else {
				str = "重名";
			}
		}
		response.getWriter().print(str);
		
	}

	/**
	 * 准备增加
	 */
	protected void readyAddProduct(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		// 类别
		CategorysServiceImpl cs = new CategorysServiceImpl();
		List<Categorys> cateList = cs.findCategorys();

		// 供应商
		ProviderServiceImpl prod = new ProviderServiceImpl();
		List<Providers> proList = prod.findProviders();

		request.setAttribute("cateList", cateList);
		request.setAttribute("proList", proList);
		request.getRequestDispatcher("addProduct.jsp").forward(request, response);
	}
	
	/**
	 *  开始增加
	 */
	protected void doAddProduct(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		PrintWriter out = response.getWriter();
		String productName = request.getParameter("proName"); // 商品名称
		// System.out.println(productName);
		double incomePrice = Double.parseDouble(request.getParameter("incomePrice")); // 进价
		int quantity = Integer.parseInt(request.getParameter("quantity"));  // 数量
		double salesPrice = Double.parseDouble(request.getParameter("salesPrice")); // 售价

		int providerId = Integer.parseInt(request.getParameter("providerId")); // 供应商id
		int categoryId = Integer.parseInt(request.getParameter("categoryId")); // 类别id
		int i = ps.addProducts(new Products(productName, incomePrice, quantity, salesPrice, new Providers(providerId),
				new Categorys(categoryId)));
		
		// 获取到Page ,得到最后一页
		Page<Products> page = new Page<Products>();
		System.out.println(i+" +++++ ");
		if(i == 300) {
			out.write("<script>alert('提示信息: 有空字符.');location.href='productServlet?op=readyAddProduct';</script>");
		} else if(i == 301) {
			out.write("<script>alert('提示信息: 已有商品名.');location.href='productServlet?op=readyAddProduct';</script>");
		} else if(i == 302) {
			out.write("<script>alert('提示信息: 添加商品成功.');location.href='seachProduct.jsp';</script>");
		}
		

	}
	
	/**
	 *  准备修改
	 */
	protected void readyEditProductById(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		int id = Integer.parseInt(request.getParameter("id"));
		// 商品
		Products p = ps.findProductById(id);
		
		// 类别
		CategorysServiceImpl cs = new CategorysServiceImpl();
		List<Categorys> cateList = cs.findCategorys();
		
		// 供应商
		ProviderServiceImpl prod = new ProviderServiceImpl();
		List<Providers> proList = prod.findProviders();
		
		
		request.setAttribute("p", p);
		request.setAttribute("cateList", cateList);
		request.setAttribute("proList", proList);
		request.getRequestDispatcher("editProductById.jsp").forward(request, response);
	}
	
	/**
	 *  开始修改
	 */
	protected void doEditProductById(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		
		int productId = Integer.parseInt(request.getParameter("proId"));
		String productName = request.getParameter("proName");
		// System.out.println(productName);
		double incomePrice = Double.parseDouble(request.getParameter("incomePrice"));
		int quantity = Integer.parseInt(request.getParameter("quantity"));
		double salesPrice = Double.parseDouble(request.getParameter("salesPrice"));
		String dateStr = request.getParameter("incomeTime");
		Date incomeTime = null;;
		try {
			incomeTime = new SimpleDateFormat("yyyy-mm-dd").parse(dateStr);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		System.out.println(incomeTime);
		
		int providerId = Integer.parseInt(request.getParameter("providerId"));
		int categoryId = Integer.parseInt(request.getParameter("categoryId"));
		
		int i = ps.modifyProductsById(new Products(productId, productName, incomePrice, quantity, salesPrice, incomeTime, new Providers(providerId), new Categorys(categoryId)));
		
		// request.setAttribute("i", i);
		PrintWriter out = response.getWriter();
		
		if (i == 302) {
			// request.getRequestDispatcher("productServlet?op=showProductByPage&currentPage=1&pageSize=5").forward(request, response);
			out.write("<script>alert('提示信息: 商品修改成功.');location.href='seachProduct.jsp';</script>");
			// System.out.println("----------提示信息: 商品修改成功----------");
		} else if (i == 301) {
			out.write("<script>alert('提示信息: 商品修改失败(商品名可能重复).');location.href='editProductById.jsp';</script>");
			// System.out.println("----------提示信息: 商品修改失败(商品名可能重复)----------");
		} else if (i == 300) {
			out.write("<script>alert('提示信息: 商品修改失败(有空字符串或非法字符).');location.href='editProductById.jsp';</script>");
			// System.out.println("----------提示信息: 商品修改失败(有空字符串或非法字符)----------");
		} else if (i == 303) {
			out.write("<script>alert('提示信息: 商品修改失败(可能没有该商品).');location.href='seachProduct.jsp';</script>");
			// System.out.println("----------提示信息: 商品修改失败(可能没有该商品)----------");
		}
	}
	

	/**
	 * 分页查询
	 */
	protected void showProductByPage(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 获取到 url 上传过来的当前页 和 页大小
		int currentPage = Integer.parseInt(request.getParameter("currentPage"));
		int pageSize = Integer.parseInt(request.getParameter("pageSize"));

		Page<Products> page = ps.findProductsListByPage(new Page<Products>(currentPage, pageSize));

		// 使用 request 域对象 进行存储 ( 优势 : 数据只存在一次 请求当中 , 请求结束后 数据清除 )
		request.setAttribute("page", page);

		// 使用 转发 ( 优势 : 可以携带 本次 请求的数据 )
		request.getRequestDispatcher("showAllProducts.jsp").forward(request, response);
	}

	/**
	 * 根据id 删除商品
	 */
	protected void removeProductByproId(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		PrintWriter out = response.getWriter();
		int productId = Integer.parseInt(request.getParameter("id"));
		boolean b = ps.removeProductsById(productId);
		if(b) {
			// request.getRequestDispatcher("productServlet?op=showProductByPage&currentPage=1&pageSize=5").forward(request, response);
			out.write("<script>alert('提示信息: 商品删除成功.');location.href='seachProduct.jsp';</script>");
		} else {
			out.write("<script>alert('提示信息: 商品删除失败.');</script>");
		}

	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
